package com.openthinks.joyniproject.exception;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.openthinks.joyniproject.utils.JsonUtil;


/**
 * 统一异常处理
 * @author Administrator
 *
 */
public class FrameExceptionResolver extends SimpleMappingExceptionResolver {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(FrameExceptionResolver.class);
	
	protected @ResponseBody ModelAndView  doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		String viewName = determineViewName(ex, request);
		if (viewName != null && !viewName.equals("")) {
			// Apply HTTP status code for error views, if specified.
			// Only apply it if we're processing a top-level request.
			Integer statusCode = determineStatusCode(request, viewName);
			if (statusCode != null) {
				applyStatusCodeIfPossible(request, response, statusCode);
			}
			return getModelAndView(viewName, ex, request);
		//处理.action后缀请求异常
		} else if (request.getRequestURL().toString().endsWith(".action")){
			response.setContentType("text/html"); 
			response.setCharacterEncoding("utf-8"); 
			Map<String,Object> msg = new HashMap<String,Object>(2);
			msg.put("message", ex.getMessage());
			msg.put("success", false);
			try {
				logger.error(ex.getMessage(), ex);
				response.getWriter().write(JsonUtil.objectToJson(msg));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return new ModelAndView();
		//处理.page后缀请求异常
		} else if (request.getRequestURL().toString().endsWith(".page")){
			logger.error(ex.getMessage(), ex);
			ModelAndView model = new ModelAndView("/error");
			model.addObject("message", ex.getMessage());
			return model;
		//处理其他请求异常
		} else {
			logger.error(ex.getMessage(), ex);
			ModelAndView model = new ModelAndView("/error");
			model.addObject("message", ex.getMessage());
			return model;
		}
	}

}
